﻿using wscf.lightblue;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

namespace wscf.lightblue.Test
{
	[TestClass()]
	public class TestUtil
	{
		[AssemblyInitialize()]
		public static void AssemblyInit(TestContext context)
		{
			try
			{
				// Fails when using TestDriven
				using (FileStream stream = new FileStream("wscf.lightblue.Test.Common.dll", FileMode.Create))
				{
					using (BinaryWriter writer = new BinaryWriter(stream))
					{
						byte[] assemblyData = ReadBytesFromStream("wscf.lightblue.Test.wscf.lightblue.Test.Common.dll");
						writer.Write(assemblyData);
						writer.Close();
					}
				}
			}
			catch
			{
			}

			XmlDocument xdoc = new XmlDocument();
			Assembly _assembly = Assembly.LoadFrom("wscf.lightblue.Test.Common.dll");
			using (StreamReader sr = new StreamReader(_assembly.GetManifestResourceStream("wscf.lightblue.Test.Common.Common.MessageHeaders v1.xsd"), Encoding.UTF8))
			{
				xdoc.LoadXml(sr.ReadToEnd());
				xdoc.Save("Common.MessageHeaders v1.xsd");
			}
			using (StreamReader sr = new StreamReader(_assembly.GetManifestResourceStream("wscf.lightblue.Test.Common.Common.Fault v1.xsd"), Encoding.UTF8))
			{
				xdoc.LoadXml(sr.ReadToEnd());
				xdoc.Save("Common.Fault v1.xsd");
			}
			using (StreamReader sr = new StreamReader(_assembly.GetManifestResourceStream("wscf.lightblue.Test.Common.Common.Types v1.xsd"), Encoding.UTF8))
			{
				xdoc.LoadXml(sr.ReadToEnd());
				xdoc.Save("Common.Types v1.xsd");
			}

			_assembly = Assembly.GetExecutingAssembly();
			using (StreamReader sr = new StreamReader(_assembly.GetManifestResourceStream("wscf.lightblue.Test.WS_0001_Person v1.xsd"), Encoding.UTF8))
			{
				xdoc.LoadXml(sr.ReadToEnd());
				foreach(XmlElement e in xdoc.GetElementsByTagName("xs:import"))
				{
					e.Attributes["schemaLocation"].Value = e.Attributes["schemaLocation"].Value.Replace(@"..\wscf.lightblue.Test.Common\", "");
				}
				xdoc.Save("WS_0001_Person v1.xsd");
			}

			using (StreamReader sr = new StreamReader(_assembly.GetManifestResourceStream("wscf.lightblue.Test.WS_0001_Person v1.wsdl"), Encoding.UTF8))
			{
				xdoc.LoadXml(sr.ReadToEnd());
				foreach (XmlElement e in xdoc.GetElementsByTagName("xsd:import"))
				{
					e.Attributes["schemaLocation"].Value = e.Attributes["schemaLocation"].Value.Replace(@"..\wscf.lightblue.Test.Common\", "");
				}
				xdoc.Save("WS_0001_Person v1.wsdl");
			}

		}

		static private byte[] ReadBytesFromStream(string streamName)
		{
			using (System.IO.Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(streamName))
			{
				byte[] result = new byte[stream.Length];
				stream.Read(result, 0, (int)stream.Length);
				return result;
			}
		}

	}
}
